package org.example.egweibo8.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.egweibo8.common.respones.JsonResult;
import org.example.egweibo8.mapper.WeiboMapper;
import org.example.egweibo8.pojo.dto.WeiboDTO;
import org.example.egweibo8.pojo.entity.Weibo;
import org.example.egweibo8.pojo.vo.UserVO;
import org.example.egweibo8.pojo.vo.WeiboDetailVO;
import org.example.egweibo8.pojo.vo.WeiboVO;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags = "02.微博模块")
@RequestMapping("/v1/weibo/")
@Slf4j
@Validated
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;

    @ApiOperation("发布微博")
    @PostMapping("insert")
    public JsonResult insertWeibo(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session){
        log.debug("weiboDTO = " + weiboDTO);

        UserVO userVO = (UserVO) session.getAttribute("user");

        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO,weibo);
        weibo.setUserId(userVO.getId());
        weibo.setCreated(new Date());

        weiboMapper.insertWeibo(weibo);
        return JsonResult.ok();
    }

    @ApiOperation("微博首页列表")
    @GetMapping("selectIndex")
    public JsonResult selectIndex(){
        List<WeiboVO> weiboVOS = weiboMapper.selectIndex();
        return JsonResult.ok(weiboVOS);
    }

    @ApiOperation("微博详情页")
    @GetMapping("selectById")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "id", value = "微博编号", dataType = "long", required = true),
                                @ApiImplicitParam(name = "username", value = "用户名", dataType = "string")                            })
    public JsonResult selectById(@Range(min = 1, message = "微博id不能小于1") @RequestParam Integer id, String username){
        log.debug("id = " + id + ", username = " + username);

        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id,username);

        return JsonResult.ok(weiboDetailVO);
    }
}
